<template>
  <div class="index">
    <!-- 页面顶部 -->
    <div class="header">
      <div class="logo">
        <img src="../assets/images/logo.png" height="46" />
      </div>
      <div class="name"><span>大连百炼数字化制造系统</span></div>
      <div style="flex: 1"></div>

      <div class="title">
        <span class="el-dropdown-link"> 欢迎，{{ loginUser.userName }} </span>
        <span v-for="(role, index) in loginUser.roles" :key="index">{{ role }} </span>
      </div>

      <!-- 消息通知 -->
      <div class="title" style="margin-top: 11px">
        <el-badge :value="un_checked_number">
          <el-button type="warning" size="mini" @click="showMessageDrawer">消息通知</el-button>
        </el-badge>
      </div>
      <el-drawer title="消息通知" :visible.sync="messageVisible" direction="rtl" size="35%" :append-to-body="true">
        <div style="padding-left: 10px;">
          <el-button type="primary" size="mini" @click="checkUserMessage">全部已读</el-button>
        </div>
        <el-table :data="message_list" style="width: 100%">
          <el-table-column align="center" width="70">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.state == 0" type="danger">{{ scope.row.messageState }}</el-tag>
              <el-tag v-if="scope.row.state == 1" type="success">{{ scope.row.messageState }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="时间" width="140"> </el-table-column>
          <el-table-column prop="message" label="消息" ming-width="150"> </el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="processMessage(scope.row)">详情处理</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-drawer>

      <!-- 修改密码 -->
      <div style="margin-top: 11px; margin-right: 10px" @click="changePassword">
        <el-button type="success" size="mini">修改密码</el-button>
      </div>
      <change-password ref="changePassword" />

      <!-- 退出系统 -->
      <div style="margin-top: 11px; margin-right: 10px" @click="logout">
        <el-button type="danger" size="mini">退出</el-button>
      </div>
    </div>

    <div class="header-line"></div>

    <div class="center">
      <div class="aside" style="margin-top: 10px">
        <nav-menu></nav-menu>
      </div>

      <div class="main" :class="isCollapse ? 'collapse-main' : ''">
        <transition name="el-zoom-in-top">
          <router-view />
        </transition>
      </div>
    </div>

    <div class="footer">大连百炼数字化制造系统 技术支持：<span>&nbsp;&copy;大连海事大学百炼数字化项目组</span></div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
import { State, namespace } from 'vuex-class'
import { logout } from '@/api/login'
// 引入用户消息获取接口
import { getMessageOnUser, checkMessageApi, checkMessageOnUser, countUserUncheckMessage, getSimpleDateByDispatchForm } from '@/api/message/message'
// 获取通知单接口
import { getNotice } from '@/api/notice'
// 引入 element-ui 消息提示组件
import { Notification } from 'element-ui'

import NavMenu from '@/views/_common/NavMenu.vue'
import ChangePassword from '@/views/login/changePassword.vue'
import dayjs from 'dayjs'

const vuexLogin = namespace('Login')
const vuexDispatchDetail = namespace('DispatchDetail')
@Component({
  components: {
    NavMenu,
    ChangePassword
  }
})
export default class Index extends Vue {
  @vuexLogin.State loginUser: any
  @vuexLogin.State isAdmin: any
  @State isCollapse: any
  public $refs!: {
    fullscreenButton: any
    changePassword: any
  }
  collapsed: any = '0'

  // 消息面板开闭控制
  messageVisible: boolean = false
  // 用户消息列表
  message_list: any = []
  // 用户消息列表未读消息数量
  un_checked_number: number = 0
  // 获取消息请求时间
  time_of_request_message: any = new Date()

  // 进入派工单详情页面的产品ID
  @vuexDispatchDetail.Mutation setProducingId

  created() {
    this.countUncheckMessage()
  }

  /**
   * 统计用户未读消息数量
   */
  private async countUncheckMessage() {
    let res = await countUserUncheckMessage({})
    if (res) {
      this.un_checked_number = Number(res.data)
    }
  }

  /**
   * 打开用户消息弹框 并获取用户消息
   */
  private showMessageDrawer() {
    this.getUserMessage()
    this.messageVisible = true
  }

  /**
   * 获取用户消息
   */
  private async getUserMessage() {
    let res = await getMessageOnUser({}).catch(err => {
      Notification.error(err)
    })
    if (res) {
      this.message_list = res.data
      this.time_of_request_message = Date.now()
    }
  }

  /**
   * 消息处理（单条）
   */
  processMessage(message) {
    // 设置消息已读
    this.checkMessage(message.messageId)
    // 判断消息主题：派工单相关进入派工详情页面
    if (message.topicId == 3) {
      this.messageVisible = false
      this.routeToDispatchDetail(message.objId)
    }
    // 判断消息主题：通知单相关进入通知单详情页面
    else if (message.topicId == 2) {
      this.messageVisible = false
      this.routeToNoticeDetail(message.objId)
    }
    // 判断消息主题：客户信息相关进入客户信息列表页面
    else if (message.topicId == 4 || message.topicId == 5) {
      this.messageVisible = false
      this.routeToFapiaoHeader()
    }
    // 其他状态
    else {
      this.getUserMessage()
    }
  }

  /**
   * 跳转至派工单详情页面
   */
  async routeToDispatchDetail(dispatchFormId) {
    // 派工单详情页面需要producingId/noticeNumber/workingNumber
    // TODO 页面间交互逻辑混乱 需要重构梳理
    let res = await getSimpleDateByDispatchForm({ dispatchFormId: dispatchFormId }).catch(err => {
      Notification.error(err)
    })
    if (res) {
      this.setProducingId(res.data.producingId)
      console.log('this.$route.path')
      console.log(this.$route.path)
      this.$router.push({ name: 'emptyPage' })
      let param1 = res.data.noticeNumber
      let param2 = res.data.workingNumber
      setTimeout(() => {
        this.$router.push(
          {
            name: 'dispatch-details',
            params: {
              from: 'list',
              formId: dispatchFormId,
              noticeNumber: param1,
              workingNumber: param2
            }
          },
          () => {
            console.log('回调函数111')
          },
          () => {
            console.log('回调函数222')
          }
        )
      }, 300)
    }
  }

  async routeToNoticeDetail(noticeId) {
    // 通知单详情页面需要 notice 数据
    // TODO 页面间交互逻辑混乱 需要重构梳理
    let res = await getNotice({ noticeId: noticeId }).catch(err => {
      Notification.error(err)
    })
    if (res) {
      this.$router.push({ name: 'emptyPage' })
      let row = res.data
      setTimeout(() => {
        this.$router.push(
          {
            name: 'detail',
            params: { typeNumber: '1', row, showApproval: 'false', showReview: 'false', showBtn: 'true', showDao: 'true' }
          },
          () => {
            console.log('回调函数111')
          },
          () => {
            console.log('回调函数222')
          }
        )
      }, 300)
    }
  }

  async routeToFapiaoHeader() {
    this.$router.push({ name: 'fapiao-header' })
  }
  /**
   * 设置消息已读
   */
  private async checkMessage(messageId) {
    await checkMessageApi({ messageId: messageId })
      .catch(err => {
        Notification.error(err)
      })
      .then(() => {
        this.countUncheckMessage()
      })
  }
  private async checkUserMessage() {
    let time = dayjs(this.time_of_request_message).format('YYYY-MM-DD HH:mm:ss')
    await checkMessageOnUser({ lastRequestTime: time })
      .catch(err => {
        Notification.error(err)
      })
      .then(() => {
        this.countUncheckMessage()
      })
    this.messageVisible = false
  }

  /**
   * 修改密码：打开弹框
   */
  changePassword() {
    this.$refs.changePassword.open(this.loginUser.userName)
  }

  /**
   * 退出系统
   */
  logout() {
    localStorage.removeItem('auto_login')
    sessionStorage.removeItem('token')
    logout({ username: this.loginUser.userName })
      .then(res => {})
      .catch(err => {
        this.$message.error(err.msg)
      })

    this.$router.push('/')
    this.$message.warning('已成功退出系统！')
  }

  mounted() {
    let isFirstTime = sessionStorage.getItem('loginTimes')
    if (isFirstTime == '1') {
      this.$message.warning('第一次登录请修改密码')
      setTimeout(() => {
        this.changePassword()
      }, 1000)
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.scss';
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}
.index {
  width: 100%;
  // height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  .header {
    width: 100%;
    height: $headerHeight;
    // background: #004098;
    // background-image: url(../assets/images/header.jpg);
    background-repeat: no-repeat;
    background-position-x: right;
    background-color: #fff;
    z-index: 1001;
    color: #000;
    display: flex;
    flex-direction: row;
    position: fixed;
    top: 0;
    left: 0;
    .logo {
      width: 50px;
      height: 50px;
      line-height: 50px;
      padding-left: 25px;
      margin-top: 4px;
    }
    .name {
      width: 300px;
      height: 50px;
      line-height: 50px;
      padding-left: 20px;
      font-weight: bold;
      font-size: 18px;
    }
    .btn {
      // width: 50px;
      padding: 0 15px;
      // height: 50px;
      text-align: center;
      // line-height: 50px;
      background: transparent;
      transition: all 0.4s ease;
      cursor: pointer;
      &:hover {
        // background: #3366ad;
        // background: rgba(152, 181, 223, 0.6);
        background: #e60013;
        color: #fff;
      }
      i {
        font-size: 18px;
        line-height: 50px;
      }
      .fullscreen {
        font-size: 14px;
        color: #eee;
        &:hover {
          color: #fff;
        }
      }
      .badge {
        .el-badge__content {
          &.is-fixed {
            top: 15px;
            right: 5px;
          }
        }
      }
    }
    .user {
      height: 50px;
      padding: 0 10px 0 15px;
      font-weight: bold;
      cursor: pointer;
      .el-dropdown {
        color: #000;
        &:hover {
          color: #fff;
        }
      }
      &:hover {
        background: #e60013;
      }

      .el-dropdown-link {
        line-height: 50px;
        font-size: 14px;
      }
    }
  }
  .title {
    height: 50px;
    padding: 0 10px 0 15px;
    font-weight: bold;
    cursor: pointer;
    .el-dropdown {
      color: #000;
    }
    .el-dropdown-link {
      line-height: 50px;
      font-size: 14px;
    }
  }
  .header-line {
    width: 100%;
    height: 10px;
    position: fixed;
    margin-top: $headerHeight;
    background: #fafafa;
  }
  .center {
    // width: 100%;
    // height: calc(100% - 80px);
    // display: flex;
    // flex-direction: row;
    // // flex: 1;
    // // background: #ddd;
    // position: relative;
    // .collapse {
    //   position: absolute;
    //   top: 50%;
    //   bottom: 50%;
    //   left: $sideBarWidth;
    //   margin-top: -20px;
    //   width: 6px;
    //   height: 40px;
    //   background: #efefef;
    //   border: 1px solid #e4e7ed;
    //   border-left: none;
    //   border-top-right-radius: 10px;
    //   border-bottom-right-radius: 10px;
    //   transition: all 0.2s ease;
    //   cursor: pointer;
    //   i {
    //     position: absolute;
    //     top: 14px;
    //     left: -3px;
    //     font-size: 12px;
    //     color: #ccc;
    //   }
    //   &:hover {
    //     background: #ddd;
    //   }
    //   &:hover i {
    //     color: #666;
    //   }
    // }
    // .collapsed {
    //   width: 0;
    // }
    .main {
      // width: calc(100% - #{$sideBarWidth});
      margin-left: $sideBarWidth;
      margin-bottom: $footerHeight;
      margin-top: $headerHeight + 10px;
      height: calc(100vh - #{$footerHeight} - #{$headerHeight} - 10px);
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      background: #fafafa;
      transition: width 0.4s ease;
      position: relative;
      overflow: auto !important;
      // min-height: calc(100vh - $footerHeight - $headerHeight)
    }
    .collapse-main {
      margin-left: $sideBarCollapseWidth !important;
      width: calc(100% - 60px);
    }
  }
  .footer {
    z-index: 1001;
    width: 100%;
    height: $footerHeight;
    line-height: $footerHeight;
    padding-left: 20px;
    position: fixed;
    left: 0;
    bottom: 0;
    // border-top: 1px solid #ccc;
    background: #fafafa url(../assets/images/line1.png) repeat-x;
    text-align: left;
    color: #999;
    font-size: 12px;
    a {
      color: #666;
      text-decoration: none;
      &:hover {
        color: #369;
      }
    }
    span {
      color: #ccc;
    }
  }
}
</style>
